<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-05-26
 * Time: 16:05
 */

namespace app\common\model;


use app\common\exception\CategoryException;
use app\common\exception\ParameterException;
use app\common\validate\IDCollection;
use service\TreeService;
use think\model\concern\SoftDelete;
use app\common\validate\Category as Validate;

class Category extends BaseModel
{
    protected $hidden = ['create_time','update_time','delete_time'];

    // 使用软删除
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    public function getLabelAttr($value, $data)
    {
        return $data['title'];
    }

    /**
     * 获取栏目的分页数据
     * @param array $params
     * @return \think\Paginator
     */
    public static function getTableTreeData(array $params)
    {
        $static = new static();

        $static = $static->order(['sort'=>'ASC']);

        foreach ($params as $name => $value) {
            $value = !is_array($value) ? trim($value) : $value;
            switch ($name) {
                case 'title':
                    if (!empty($value)) {
                        $like_text = '%' . $value . '%';
                        $static = $static->whereLike('title', $like_text);
                    }
                    break;
            }
        }

        $data = $static->select();

        $data = $data ? $data->toArray() : [];

        return TreeService::elementTableTree($data);
    }

    /**
     * 获取顶级栏目的数据
     * @return array
     */
    public static function getTopItemData()
    {
        $data = static::getDataWithField([['status','=',1],['pid','=',0]],['id','title'],['sort'=>'asc']);

        return $data->isEmpty() ? [] : $data->toArray();
    }

    /**
     * 获取栏目下的全部子栏目
     * @return array
     */
    public static function getAllItemData()
    {
        $data = static::getDataWithField([['status','=',1]],['id','pid','title'],['sort'=>'asc'])
            ->append(['label']);

        $data =  $data->isEmpty() ? [] : $data->toArray();

        return TreeService::elementOptionsGroup($data);
    }

    /**
     * 获取指定id下的子栏目信息
     * @param $id
     * @return array
     */
    public static function getChildrenNavByID($id)
    {
        $validate = new Validate(['pid' => 0]);
        if (!$validate->scene('get_nav')->check(['top_id' => $id])) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        $data = static::getDataWithField([['pid','=',$id],['status','=',1]],['id','title'],['sort'=>'asc']);

        if ($data->isEmpty()) {
            throw new CategoryException();
        } else {
            return $data->toArray();
        }
    }

    /**
     * 添加栏目信息
     * @param array $data
     * @return bool
     */
    public static function addCategory(array $data)
    {
        $validate = new Validate($data);
        if (!$validate->scene('add')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        $static = static::create($data);

        if (isset($static->id) && $static->id > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 编辑栏目信息
     * @param array $data
     * @return bool
     */
    public static function editCategory(array $data)
    {
        $validate = new Validate($data);
        if (!$validate->scene('edit')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        $static = static::find($data['id']);
        static::checkTopHaveChild($data['id'],$static->pid,$data['pid']);

        $result = $static->allowField(['id','pid','title','sort','status'])
            ->save($data);

        if ($result !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除栏目数据
     * @param $ids
     * @return bool
     */
    public static function delCategory($ids)
    {
        $validate = new IDCollection();
        if (!$validate->check([
            'ids' => $ids
        ])) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        // 获取全部菜单的id和pid数据
        $allCategoryData = static::getDataWithField([],['id','pid'])
            ->toArray();
        $allID = [];    //保存所有的相关id，如果是顶级节点会获取其下面的子元素
        //判断是否为数组，然后将字符串转为数组
        if (!is_array($ids)){
            $ids = explode(',',$ids);
        }
        foreach ($ids as &$id) {
            //将id数组的字符转换成整数
            $id = intval($id);
            //判断是否有重复的数据
            if (in_array($id,$allID)){
                continue;
            }

            //获取对应id下的子id
            $allID = array_merge($allID,TreeService::getChildrenPid($allCategoryData,$id,'id','pid',true));
        }
        //把主id也添加进去
        $allID = array_merge($allID,$ids);
        //去除重复值
        $allID = array_unique($allID);

        if (static::destroy($allID) !== false) {
            return true;
        } else {
            return false;
        }
    }
}